package com.aixingfu.sports.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aixingfu.sports.Adapter.PaymentAdapter;
import com.aixingfu.sports.Adapter.PaymentTypeAdapter;
import com.aixingfu.sports.Adapter.PaymetAdapter;
import com.aixingfu.sports.Adapter.RecyclerTouchListener;
import com.aixingfu.sports.MVP.contract.BuyChargeClassContract;
import com.aixingfu.sports.MVP.contract.DepositContract;
import com.aixingfu.sports.MVP.contract.DoCardUpgradeContract;
import com.aixingfu.sports.MVP.contract.UserPayContract;
import com.aixingfu.sports.MVP.presenter.BuyChargeClassPresenter;
import com.aixingfu.sports.MVP.presenter.DepositPresenter;
import com.aixingfu.sports.MVP.presenter.DoCardUpgradePresenter;
import com.aixingfu.sports.MVP.presenter.UserPayPresenter;
import com.aixingfu.sports.Model.BuyChargeClassModel;
import com.aixingfu.sports.Model.DepositModel;
import com.aixingfu.sports.Model.DoCardUpgradeModel;
import com.aixingfu.sports.Model.UserPayModel;
import com.aixingfu.sports.R;
import com.aixingfu.sports.bean.PaymentBean;
import com.aixingfu.sports.bean.PaymentMBean;
import com.aixingfu.sports.view.PopPayMethodCheckChooseID;
import com.aixingfu.sports.view.PopupWindowCheckChoose;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.orie.librarybase.base.BaseActivity;
import com.orie.librarybase.utils.MoneyEditUtils;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogSureCancel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//升级付款
@Route(path = "/main/PaymentUpgradeActivity")
public class PaymentUpgradeActivity extends BaseActivity implements UserPayContract.MyView, DepositContract.MyView, PaymentAdapter.OnItemEditTextChangedListener, BuyChargeClassContract.MyView, DoCardUpgradeContract.MyView, PaymentTypeAdapter.OnItemEditTextChangedListener {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_collect_way)
    TextView tvCollectWay;
    @BindView(R.id.ll_type)
    LinearLayout llType;
    @BindView(R.id.ll_deposit)
    LinearLayout llDeposit;
    @BindView(R.id.recycle_type)
    RecyclerView recycleType;
    @BindView(R.id.iv_add)
    ImageView ivAdd;
    @BindView(R.id.rl_add_type)
    RelativeLayout rlAddType;
    @BindView(R.id.ed_receipt_number)
    EditText edReceiptNumber;
    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.ed_deposit)
    EditText edDeposit;
    @BindView(R.id.tv_deposit)
    TextView tvDeposit;
    private UserPayPresenter userPayPresenter;
    private PaymetAdapter paymetAdapter;
    private List<PaymentBean> paymentBeansList = new ArrayList<>();
    private List<PaymentMBean> paymentMBeansList = new ArrayList<>();
    private ArrayList<String> mList = new ArrayList();
    private List<UserPayModel.DataBean.PayMethodBean> pay_method;
    private PopPayMethodCheckChooseID popPayMethodCheckChooseID;
    private int paymode;
    private int POSITION;
    private BuyChargeClassPresenter buyChargeClassPresenter;
    private PaymentAdapter paymentAdapter;
    private int mposition;
    private PaymentBean paymentBean;

    private String jsonString;
    private double dprice;
    private String order_id = "";
    private String mrmber_order_id = "";
    private String contract_id = "";
    private String receiptNumber;
    private PopupWindowCheckChoose mPopup;
    private String type = "全款";
    private DepositPresenter depositPresenter;
    private String member_id;
    private String deposit;
    private String depositMoney;
    private double mdeposit;
    private DoCardUpgradePresenter doCardUpgradePresenter;
    private RecyclerTouchListener onTouchListener;
    private PaymentTypeAdapter paymentTypeAdapter;
    @Override
    protected int provideContentViewId() {
        return R.layout.activity_payment_class;
    }

    public static void startActivityByRoute() {
        ARouter.getInstance().build("/main/PaymentUpgradeActivity").navigation();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        Bundle bundle = getIntent().getExtras();
        member_id = bundle.getString("member_id", "");
        userPayPresenter = new UserPayPresenter();
        userPayPresenter.attachView(this);
        buyChargeClassPresenter = new BuyChargeClassPresenter();
        buyChargeClassPresenter.attachView(this);
        doCardUpgradePresenter = new DoCardUpgradePresenter();
        doCardUpgradePresenter.attachView(this);
//        PaymentBean paymentBean = new PaymentBean();
//        paymentBean.setPayment("请选择支付方式");
//        paymentBean.setPrice("");
//        paymentBeansList.add(paymentBean);
        userPayPresenter.getUserPay();
//        recycleType.setLayoutManager(new LinearLayoutManager(PaymentActivity.this, LinearLayoutManager.VERTICAL, false));
//        paymetAdapter = new PaymetAdapter(PaymentActivity.this, R.layout.item_payment, paymentBeansList);
//        recycleType.addItemDecoration(new SpaceItemDecoration(0, 20));
////        //设置分割线
////        recycleList.addItemDecoration(new DividerItemDecoration(
////                getActivity(), DividerItemDecoration.VERTICAL));
//        recycleType.setAdapter(paymetAdapter);

        paymentTypeAdapter = new PaymentTypeAdapter(this, paymentBeansList);
        paymentTypeAdapter.setListener(this);
        recycleType.setAdapter(paymentTypeAdapter);
        recycleType.setLayoutManager(new LinearLayoutManager(this));
        onTouchListener = new RecyclerTouchListener(this, recycleType);
        onTouchListener.setSwipeable(true);
        onTouchListener.setClickable(true);
        MoneyEditUtils.afterDotTwo(edDeposit);
        onTouchListener
                .setClickable(new RecyclerTouchListener.OnRowClickListener() {
                    @Override
                    public void onRowClicked(int position) {
                    }
                    @Override
                    public void onIndependentViewClicked(int independentViewID, int position) {

                    }
                })
                .setLongClickable(true, new RecyclerTouchListener.OnRowLongClickListener() {
                    @Override
                    public void onRowLongClicked(int position) {
                    }
                })
                .setSwipeOptionViews( R.id.change)
                .setSwipeable(R.id.rowFG, R.id.rowBG, new RecyclerTouchListener.OnSwipeOptionsClickListener() {
                    @Override
                    public void onSwipeOptionClicked(int viewID, int position) {
                        String message = "";
                        if (viewID == R.id.change) {
                            if (position == 0){
                                return;
                            }
                            paymentBeansList.remove(position);
//                            paymentTypeAdapter.notifyItemRemoved(position);
                            paymentTypeAdapter.setList(paymentBeansList);
                            paymentTypeAdapter.notifyDataSetChanged();
                        }
                    }
                });
        paymentTypeAdapter.setOnItemClickListener(new PaymentTypeAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(int position, View v) {
                hideIputKeyboard();
                POSITION = position;
                popPayMethodCheckChooseID.showPop(recycleType);
            }
        });

//        paymentAdapter = new PaymentAdapter();
//        paymentAdapter.setListener(this);
//        recycleType.setAdapter(paymentAdapter);
//        recycleType.setLayoutManager(new LinearLayoutManager(this));
//        paymentAdapter.setOnItemClickListener(new PaymentAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(int position, View v) {
//                POSITION = position;
//                popPayMethodCheckChooseID.showPop(recycleType);
//            }
//        });

        setPaymentList();
        mList = getPopList();
        mPopup = new PopupWindowCheckChoose(PaymentUpgradeActivity.this, mList);
        mPopup.setTagTxt("请选择证件类型")//设置顶部title的内容
                .setButtomTxt("取消")//设置底部按钮内容
                .setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);//单选
        //单选
        mPopup.setOnEventLisenter(positionList -> {
            mPopup.dismiss();
            tvCollectWay.setText(mList.get(positionList.get(0)));
            type = mList.get(positionList.get(0));
            if ("全款".equals(type)){
                llDeposit.setVisibility(View.GONE);
            }else if ("使用定金".equals(type)){
                llDeposit.setVisibility(View.VISIBLE);
            }
        });
        depositPresenter = new DepositPresenter();
        depositPresenter.attachView(this);
        getDeposit();
//        paymentAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
//            @Override
//            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//                int id = view.getId();
//                if (id == R.id.ll_payment_method){
//                    POSITION = position;
//                    popPayMethodCheckChooseID.showPop(recycleType);
//                }
//            }
//        });
    }

    /**
     * 数据
     *
     * @return
     */
    public ArrayList<String> getPopList() {
        ArrayList<String> popList = new ArrayList<>();
        popList.add("全款");
        popList.add("使用定金");
        return popList;
    }

    public void setPaymentList() {
        PaymentBean paymentBean = new PaymentBean();
        paymentBean.setPayment("请选择支付方式");
        paymentBean.setPrice("");
        paymentBeansList.add(paymentBean);
        paymentTypeAdapter.setList(paymentBeansList);
    }
    private double mPrice=0;
    public void getDeposit(String receiptNumber) {
        if (buyChargeClassPresenter.isViewAttached()) {
            HashMap<String, String> map = new HashMap<>();
            if ("全款".equals(type)){
                map.put("pay_type", "1");
            }else if ("使用定金".equals(type)){
                map.put("pay_type", "2");
            }
            for (int i = 0; i < paymentBeansList.size() ; i++) {
                mPrice = mPrice + Double.parseDouble( paymentBeansList.get(i).getPrice());
            }
            map.put("renewal_now_price", String.valueOf(mPrice));
            map.put("pay_info",jsonString);
            map.put("member_id", member_id);
            map.put("earnest",deposit);
            map.put("receipt_number",receiptNumber);
           buyChargeClassPresenter.getBuyChargeClass(map);
        }
    }
    public void getDoCardUpgrade(String receiptNumber) {
        if (doCardUpgradePresenter.isViewAttached()) {
            mPrice = 0;
            HashMap<String, String> map = new HashMap<>();
            if ("全款".equals(type)){
                map.put("pay_type", "1");
            }else if ("使用定金".equals(type)){
                map.put("pay_type", "2");
            }
            for (int i = 0; i < paymentBeansList.size() ; i++) {
                String price = paymentBeansList.get(i).getPrice();
                if (TextUtils.isEmpty(price)){
                    price = "0";
                }else {
                    price = paymentBeansList.get(i).getPrice();
                }
                mPrice = mPrice + Double.parseDouble(price);
            }
            map.put("renewal_now_price", String.valueOf(mPrice));
            map.put("pay_info",jsonString);
            map.put("member_id", member_id);
            map.put("deposit_price",deposit);
            map.put("receipt_number",receiptNumber);
            doCardUpgradePresenter.getDoCardUpgrade(map);
        }
    }
    public void getDeposit() {
        if (depositPresenter.isViewAttached()) {
            HashMap<String, String> map = new HashMap<>();
            map.put("member_id", member_id);
            depositPresenter.getDeposit(map);
        }
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void beforeInit() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
    private int PAYMODE = 0;
    private PaymentMBean paymentMBean;
    @OnClick({R.id.tv_collect_way, R.id.ll_type, R.id.rl_add_type, R.id.tv_back, R.id.tv_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_collect_way:
                break;
            case R.id.ll_type:
                hideIputKeyboard();
                mPopup.showPop(tvCollectWay);
                break;
            case R.id.rl_add_type:
                hideIputKeyboard();
                PaymentBean mpaymentBean = new PaymentBean();
                mpaymentBean.setPayment("请选择支付方式");
                mpaymentBean.setPrice("");
                paymentBeansList.add(mpaymentBean);
                paymentTypeAdapter.setList(paymentBeansList);
                paymentTypeAdapter.notifyDataSetChanged();
                break;
            case R.id.tv_back:
                hideIputKeyboard();
                finish();
                break;
            case R.id.tv_next:
                hideIputKeyboard();
                dprice = 0;
                PAYMODE = 0;
                String price = "0";
                paymentMBeansList.clear();
                receiptNumber = edReceiptNumber.getText().toString();
                depositMoney = tvDeposit.getText().toString();
                deposit = edDeposit.getText().toString();
                if (llDeposit.getVisibility() == View.VISIBLE){
                    if (TextUtils.isEmpty(deposit)){
                        RxToast.normal(PaymentUpgradeActivity.this,"请输入要使用的定金金额").show();
                    }else {
                        for (int i = 0; i <paymentBeansList.size() ; i++) {
                            paymentMBean = new PaymentMBean();
                            paymentMBean.setPrice(paymentBeansList.get(i).getPrice());
                            paymentMBean.setType(paymentBeansList.get(i).getType());
                            paymentMBeansList.add(paymentMBean);
                        }
                        jsonString = JSON.toJSONString(paymentMBeansList);
                        for (int i = 0; i < paymentBeansList.size(); i++) {
                            price = paymentBeansList.get(i).getPrice();
                            String type = paymentBeansList.get(i).getType();
                            if (TextUtils.isEmpty(price)) {
                                PAYMODE = 1;
                                break;
                            } else if (TextUtils.isEmpty(type)){
                                PAYMODE = 2;
                                break;
                            }else {
                                if (TextUtils.isEmpty(price)){
                                    price = "0";
                                }else {
                                    price = paymentBeansList.get(i).getPrice();
                                }
                                double mprice =  Double.parseDouble(price);
                                this.dprice = this.dprice + mprice;
                            }
                        }
                        if (PAYMODE == 1){
                            RxToast.normal(PaymentUpgradeActivity.this,"请填写金额").show();
                        }else if (PAYMODE == 2){
                            RxToast.normal(PaymentUpgradeActivity.this,"请选择付款方式").show();
                        }else if (dprice == 0){
                            RxToast.normal(PaymentUpgradeActivity.this,"金额不能为0").show();
                        }else {
                            setDialog();
                        }
                    }
                }else {
                    for (int i = 0; i <paymentBeansList.size() ; i++) {
                        paymentMBean = new PaymentMBean();
                        paymentMBean.setPrice(paymentBeansList.get(i).getPrice());
                        paymentMBean.setType(paymentBeansList.get(i).getType());
                        paymentMBeansList.add(paymentMBean);
                    }
                    jsonString = JSON.toJSONString(paymentMBeansList);
                    for (int i = 0; i < paymentBeansList.size(); i++) {
                        price = paymentBeansList.get(i).getPrice();
                        String type = paymentBeansList.get(i).getType();
                        if (TextUtils.isEmpty(price)) {
                            PAYMODE = 1;
                            break;
                        } else if (TextUtils.isEmpty(type)){
                            PAYMODE = 2;
                            break;
                        }else {
                            if (TextUtils.isEmpty(price)){
                                price = "0";
                            }else {
                                price = paymentBeansList.get(i).getPrice();
                            }
                            double mprice =  Double.parseDouble(price);
                            this.dprice = this.dprice + mprice;
                        }

                    }
                    if (PAYMODE == 1){
                        RxToast.normal(PaymentUpgradeActivity.this,"请填写金额").show();
                    }else if (PAYMODE == 2){
                        RxToast.normal(PaymentUpgradeActivity.this,"请选择付款方式").show();
                    }else if (dprice == 0){
                        RxToast.normal(PaymentUpgradeActivity.this,"金额不能为0").show();
                    }else {
                        setDialog();
                    }
                }
                break;
        }
    }

    public void setDialog() {
        final RxDialogSureCancel rxDialogSureCancel = new RxDialogSureCancel(PaymentUpgradeActivity.this);
        rxDialogSureCancel.setTitle("提示");
        rxDialogSureCancel.setContent("确定已经收过款了吗？");
        rxDialogSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxDialogSureCancel.cancel();
            }
        });
        rxDialogSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxDialogSureCancel.cancel();
//                getDeposit(receiptNumber);
                getDoCardUpgrade(receiptNumber);
            }
        });
        rxDialogSureCancel.show();
    }

    @Override
    public void showToast(String msg, String state) {

    }

    @Override
    public void setDoCardUpgrade(DoCardUpgradeModel data) {
        if (data.getCode() == 1) {
            RxToast.normal(PaymentUpgradeActivity.this, data.message).show();
            order_id = String.valueOf(data.getData().getOrder_id());
            contract_id = String.valueOf(data.getData().getContract_id());

            ARouter.getInstance().build("/main/ConfirmContractRenewActivity").withString("order_id", order_id).withString("contract_id", contract_id).navigation();
        } else {
            RxToast.normal(PaymentUpgradeActivity.this, data.message).show();
        }
    }

    @Override
    public void setBuyChargeClass(BuyChargeClassModel data) {
//        if (data.getCode() == 1) {
//            RxToast.normal(PaymentUpgradeActivity.this,data.message).show();
//            order_id = String.valueOf(data.getData().getOrder_id());
//            mrmber_order_id = String.valueOf(data.getData().getMember_course_order_id());
//            contract_id = String.valueOf(data.getData().getContract_id());
//            ARouter.getInstance().build("/main/ConfirmContractBuyClassActivity").withString("order_id", order_id).withString("member_course_order_id",mrmber_order_id).withString("contract_id",contract_id).navigation();
//        } else {
//            RxToast.normal(PaymentUpgradeActivity.this,data.message).show();
//        }
    }


    @Override
    public void setDeposit(DepositModel data) {
        if (data.getCode() == 1) {
            mdeposit = data.getData().getDeposit();
            tvDeposit.setText(mdeposit+"");
        }
    }

    @Override
    public void setUserPay(UserPayModel data) {
        if (data.getCode() == 1) {

            pay_method = data.getData().getPay_method();
            popPayMethodCheckChooseID = new PopPayMethodCheckChooseID(PaymentUpgradeActivity.this, pay_method);
            popPayMethodCheckChooseID.setTagTxt("请选择")//设置顶部title的内容
                    .setButtomTxt("取消")//设置底部按钮内容
                    .setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);//单选
            //单选
            popPayMethodCheckChooseID.setOnEventLisenter(positionList -> {
                popPayMethodCheckChooseID.dismiss();
                paymentBean = paymentBeansList.get(POSITION);
                paymentBean.setPayment(pay_method.get(positionList.get(0)).getPay_name());
//                paymentTypeAdapter.notifyItemChanged(POSITION);

                paymentBean.setType(String.valueOf(pay_method.get(positionList.get(0)).getPay_mode()));
                paymentTypeAdapter.setList(paymentBeansList);
            });
        }
    }

    @Override
    public void showLoading() {
showLoadingDialog();
    }

    @Override
    public void hideLoading() {
dismissLoadingDialog();
    }

    @Override
    public Context getMyContext() {
        return this;
    }

    @Override
    public void onEditTextAfterTextChanged(Editable editable, int position) {
        POSITION = position;
        paymentBean = paymentBeansList.get(POSITION);
        paymentBean.setPrice(editable.toString());
        paymentTypeAdapter.setNewData(paymentBeansList);
    }
    //关闭软键盘
    public void hideIputKeyboard() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                InputMethodManager mInputKeyBoard = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                if (getCurrentFocus() != null) {
                    mInputKeyBoard.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                }
            }
        });
    }
    @Override
    protected void onResume() {
        super.onResume();
        recycleType.addOnItemTouchListener(onTouchListener); }

    @Override
    protected void onPause() {
        super.onPause();
        recycleType.removeOnItemTouchListener(onTouchListener);
    }
    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}
